package org.example.logindemo.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.logindemo.bean.User;
import org.example.logindemo.bean.UserDTO;

import org.example.logindemo.bean.UserVO;
import org.example.logindemo.constant.JwtClaimsConstant;
import org.example.logindemo.context.BaseContext;
import org.example.logindemo.properties.JwtProperties;
import org.example.logindemo.service.LoginService;
import org.example.logindemo.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.example.logindemo.result.Result;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/api/login")
    public Result<UserVO> login(@RequestBody UserDTO userDTO) {
        log.info("员工登录：{}", userDTO);
        User user = loginService.login(userDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        log.info("token：{}", token);
        //将登录者的id放到当前线程中
        BaseContext.setCurrentId(user.getId());

        UserVO userVO = UserVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .token(token)
                .message(user.getMessage())
                .success(user.isSuccess())
                .build();


        return Result.success(userVO);

    }


}
